package com.kds.fxtool.service;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.kds.fxtool.config.ApplicationConfig;
import com.kds.fxtool.dto.VersionInfoDto;
import com.kds.fxtool.feign.UpdateServiceClient;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;

public class UpdateService {
    private static final Logger logger = LoggerFactory.getLogger(UpdateService.class);

    // JDK 17 record 特性
    public record VersionInfo(String version, String downloadUrl,
                              String releaseNotes, boolean isMandatory) {

        // 从 DTO 转换
        public static VersionInfo fromDto(VersionInfoDto dto) {
            return new VersionInfo(dto.getVersion(), dto.getDownloadUrl(),
                    dto.getReleaseNotes(), dto.isMandatory());
        }

        // 转换为字符串（JDK 17 文本块）
        @Override
        public String toString() {
            return """
                   VersionInfo {
                     version: %s,
                     downloadUrl: %s,
                     mandatory: %s
                   }
                   """.formatted(version, downloadUrl, isMandatory);
        }
    }

    // 使用 CompletableFuture 的现代化更新检查器
    public static CompletableFuture<VersionInfo> checkForUpdatesAsync(String currentVersion, UpdateCheckCallback callback) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                logger.info("开始使用 OpenFeign 检查更新...");

                // 初始化 Spring 上下文
                ApplicationConfig.initialize();

                // 获取 Feign 客户端
                UpdateServiceClient updateClient = ApplicationConfig.getBean(UpdateServiceClient.class);

                // 调用远程服务
                VersionInfoDto versionDto = updateClient.getLatestVersion();

                if (versionDto != null && isNewerVersion(versionDto.getVersion(), currentVersion)) {
                    logger.info("发现新版本: {}", versionDto.getVersion());
                    VersionInfo versionInfo = VersionInfo.fromDto(versionDto);
                    callback.onUpdateAvailable(versionInfo);
                } else {
                    logger.info("当前已是最新版本");
                    callback.onNoUpdateAvailable();
                }
                return VersionInfo.fromDto(versionDto);
            } catch (Exception e) {
                logger.error("检查更新失败", e);
                callback.onCheckFailed(e.getMessage());
            }
            return null;
        });
    }

    private static boolean isNewerVersion(String latest, String current) {
        if (latest == null || current == null) {
            return false;
        }

        // JDK 17 模式匹配 instanceof
        if (latest.equals(current)) {
            return false;
        }

        String[] latestParts = latest.split("\\.");
        String[] currentParts = current.split("\\.");

        for (int i = 0; i < Math.min(latestParts.length, currentParts.length); i++) {
            try {
                int latestNum = Integer.parseInt(latestParts[i]);
                int currentNum = Integer.parseInt(currentParts[i]);

                if (latestNum > currentNum) return true;
                if (latestNum < currentNum) return false;
            } catch (NumberFormatException e) {
                // 如果解析失败，比较字符串
                int compare = latestParts[i].compareTo(currentParts[i]);
                if (compare > 0) return true;
                if (compare < 0) return false;
            }
        }

        return latestParts.length > currentParts.length;
    }

    // 回调接口（函数式接口）
    public interface UpdateCheckCallback {
        void onUpdateAvailable(VersionInfo versionInfo);
        void onNoUpdateAvailable();
        void onCheckFailed(String errorMessage);
    }

//
//    // 下载服务（修复版）
//    public static class DownloadUpdateService extends Service<Void> {
//        private final String downloadUrl;
//        private final String savePath;
//
//        public DownloadUpdateService(String downloadUrl, String savePath) {
//            this.downloadUrl = downloadUrl;
//            this.savePath = savePath;
//        }
//
//        @Override
//        protected Task<Void> createTask() {
//            return new Task<Void>() {
//                @Override
//                protected Void call() throws Exception {
//                    updateMessage("准备下载...");
//                    updateProgress(0, 100);
//
//                    // 模拟下载过程
//                    for (int i = 0; i <= 100; i += 10) {
//                        if (isCancelled()) {
//                            break;
//                        }
//
//                        Thread.sleep(200);
//                        updateProgress(i, 100);
//                        updateMessage("下载中... " + i + "%");
//                    }
//
//                    if (!isCancelled()) {
//                        updateMessage("下载完成");
//                        updateProgress(100, 100);
//                    }
//
//                    return null;
//                }
//            };
//        }
//    }
}